import json

# 下面两行是同步的方式才需要导入的
# from asgiref.sync import async_to_sync
# from channels.generic.websocket import WebsocketConsumer

# 异步
from channels.generic.websocket import AsyncWebsocketConsumer


# class ChatConsumer(WebsocketConsumer):
#     """没有使用 channel layer 的 Consumer"""
#     def connect(self):
#         self.accept()

#     def disconnect(self, close_code):
#         pass

#     def receive(self, text_data):
#         text_data_json = json.loads(text_data)
#         message = text_data_json['message']

#         self.send(text_data=json.dumps({
#             'message': "Hi: " + message
#         }))

# class ChatConsumer(WebsocketConsumer):
#     """使用 channel layer 的 Consumer，同步的方式"""
#     def connect(self):
#         self.room_name = self.scope['url_route']['kwargs']['room_name']
#         self.room_group_name = 'chat_{}'.format(self.room_name)

#         # join room group
#         async_to_sync(self.channel_layer.group_add)(
#             self.room_group_name,
#             self.channel_name
#         )

#         self.accept()

#     def disconnect(self, close_code):
#         # leave the group
#         async_to_sync(self.channel_layer.group_discard)(
#             self.room_group_name,
#             self.channel_name
#         )

#     # receive message from websocket
#     def receive(self, text_data):
#         print('text_data is: ', text_data)
#         text_data_json = json.loads(text_data)
#         print('text_data_json: ', text_data_json)
#         message = text_data_json['message']

#         # send message to room group
#         self.send(text_data=json.dumps({
#             'message': "Hi: " + message
#         }))
#         async_to_sync(self.channel_layer.group_send)(
#             self.room_group_name,
#             {
#                 'type': 'chat_message',
#                 'message': 'Hi: ' + message
#             }
#         )

#     # receive message from room group
#     def chat_message(self, event):
#         print('event is: ', event)
#         message = event['message']

#         # send message to websocket
#         self.send(text_data=json.dumps({
#             'message': message
#         }))


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))